<?php
	header('Content-Type: text/html; charset=utf-8');
	require_once("videoInfo.php");

	//Class to be a JSON
	class Video{
		var $watch;
		var $thumbnail;
		var $titulo;
		var $videoId;
		var $rating;
	}
	class ResultadoBusca{
		var $startOffset;
		var $endOffset;
		var	$total;
		var $links;
		var $vs = array();
	}

	$resultado = new ResultadoBusca();
    // if form not submitted
    // display search box
    
	// check for search keywords
	// trim whitespace
	// encode search string
	if (!isset($_GET['vq']) || empty($_GET['vq'])) {
		die ('ERROR: Please enter one or more search keywords');
	} else {
		$vq = $_GET['vq'];
		$vq = ereg_replace('[[:space:]]+', ' ', trim($vq));
		$vq = urlencode($vq);
	}
      
	// set max results per page
	if (!isset($_GET['i']) || empty($_GET['i'])) {
		$i = 25;
	} else {
		$i = htmlentities($_GET['i']);
	}
      
      // set sort critera
	if (!isset($_GET['s']) || empty($_GET['s'])) {
		$s = 'viewCount';
	} else {
		$s = htmlentities($_GET['s']);
	}
      
	// set start index
	if (!isset($_GET['pageID']) || $_GET['pageID'] <= 0) {
		$o = 1;  
	} else {        
		$pageID = htmlentities($_GET['pageID']);
		$o = (($pageID-1) * $i)+1;  
	}
      
	// generate feed URL
	$feedURL = "http://gdata.youtube.com/feeds/api/videos?vq={$vq}&orderby={$s}&max-results={$i}&start-index={$o}";

	// read feed into SimpleXML object
	$sxml = getXmlFromUrl($feedURL);
	// var_dump($sxml);die();
	// get summary counts from opensearch: namespace
	$counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
	$total = $counts->totalResults; 
	$startOffset = $counts->startIndex; 
	$endOffset = ($startOffset-1) + $counts->itemsPerPage;       

	// include Pager class
	require_once 'Pager/Pager.php';
	$params = array(
		'mode'       => 'Jumping',
		'perPage'    => $i,
		'delta'      => 5,
		'totalItems' => $total,
	);
	$pager = & Pager::factory($params);
	$links = $pager->getLinks();
	$resultado->total = $total . "";
	$resultado->startOffset = $startOffset . "";
	$resultado->endOffset = $endOffset . "";
	$resultado->links = $links['all'];
	// iterate over entries in resultset
	// print each entry's details
	foreach ($sxml->entry as $entry) {
		// get nodes in media: namespace for media information
		$media = $entry->children('http://search.yahoo.com/mrss/');

		// get video player URL
		$attrs = $media->group->player->attributes();
		$watch = $attrs['url']; 

		// get video thumbnail
		if ($media->group->thumbnail && $media->group->thumbnail[0]->attributes()) {
			$attrs = $media->group->thumbnail[0]->attributes();
			$thumbnail = $attrs['url']; 
		}

		// get <yt:duration> node for video length
		$yt = $media->children('http://gdata.youtube.com/schemas/2007');
		$attrs = $yt->duration->attributes();
		$length = $attrs['seconds']; 

		// get <yt:stats> node for viewer statistics
		$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
		if($yt->statistics && $yt->statistics->attributes()){
			$attrs = $yt->statistics->attributes();
			if(isset($attrs) && isset($attrs['viewCount'])){
				$viewCount = $attrs['viewCount']; 
			}
		}
		// get <gd:rating> node for video ratings
		$gd = $entry->children('http://schemas.google.com/g/2005'); 
		if ($gd->rating) {
			$attrs = $gd->rating->attributes();
			$rating = $attrs['average']; 
		} else {
			$rating = 0; 
		}

		// get video ID
		$arr = explode('/',$entry->id);
		$id = $arr[count($arr)-1];
		
		$video = new Video();
		$video->thumbnail = $thumbnail . ""; //cast way of life or $video->thumbnail = (string)$thumbnail;
		$video->watch = $watch . "";
		$video->titulo = $media->group->title . "";
		$video->rating = $rating . "";
		$video->viewCount = $viewCount . "";
		$video->videoId = $id. "";
		
		$resultado->vs[]=$video;
	}
	echo json_encode($resultado);
?>